package org.logan.sample.base.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;

/**
 * 日期工具类
 * @ClassName: DateUtil 
 * @author zhaoyy
 * @date 2013-12-30 上午12:14:55 
 *
 */
public final class DateUtil {
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private DateUtil() {
    };

    /**
     * 日期转字符串;
     * @Title: dateToString 
     * @throws
     */
    public static String dateToString(Date date, String pattern) {
        String dateResult = null;
        if (date != null) {
            SimpleDateFormat f = new SimpleDateFormat(StringUtils.isNotEmpty(pattern) ? pattern : "yyyy-MM-dd");
            dateResult = f.format(date);
        }
        return dateResult;
    }

    /**
     * 日期转字符串;
     * @Title: dateToString 
     * @throws
     */
    public static String dateToString(Date date) {
        String dateResult = null;
        if (date != null) {
            dateResult = format.format(date);
        }
        return dateResult;
    }

    /**
     * 字符串转成日期;
     * @Title: stringToDate 
     * @throws
     */
    public static Date stringToDate(String date) {
        Date dateResult = null;
        try {
            if (date != null && "" != date) {
                dateResult = format.parse(date);
            }
            return dateResult;
        } catch (ParseException e) {
            e.printStackTrace();
            dateResult = getNowDate();
        }
        return dateResult;
    }

    /**
     * 根据传递过来的时间获取指定日期的格式;
     * @Title: getNowDate 
     * @throws
     */
    public static Date dateToDate(Date date) {
        String currDate = null;
        if (date != null) {
            currDate = dateToString(date);
        }
        return stringToDate(currDate);
    }

    /**
     * 获取当前日期,并且转换成指定格式;
     * @Title: getNowDate 
     * @throws
     */
    public static Date getNowDate() {
        String currDate = dateToString(new Date());
        return stringToDate(currDate);
    }

    /**
     * 获取当前日期,并且转换成指定格式;
     * @Title: getNowDate 
     * @throws
     */
    public static String getNowDateAsString() {
        String currDate = dateToString(new Date());
        return currDate;
    }
}
